//全局变量 NCUTCAT
global.NCUTCAT = {};

//全局仅限本地配置
NCUTCAT.localProperty = {};

//错误记录
NCUTCAT.allError = 0;

const fs = require("fs");
const fsex = require("fs-extra");
const express = require("express");


require("./core/tools"); //NCUTCAT.tools

//配置文件初始化
const CONFIG_PATH = "./property.js";
if (!fs.existsSync(CONFIG_PATH)) { //初始化
    NCUTCAT.tools.mCopyFileSync("./model/property.js", CONFIG_PATH);
}
require("./model/property");
require("./property");

require("./core/log");

//控制台颜色
const colors = require("colors");
colors.setTheme({
    silly: "rainbow",
    input: "grey",
    verbose: "cyan",
    prompt: "red",
    info: "green",
    data: "blue",
    help: "cyan",
    warn: "yellow",
    debug: "magenta",
    error: "red"
});



const dm = require("./core/DataManager"); //数据管理初始化
const fm = require("./core/FileManager"); //文件管理初始化
const um = require("./core/UserManager"); //用户管理初始化
const mm = require("./core/MailManager"); //邮件管理初始化

global.RES_CHECKER = obj => {
    if (obj.success === undefined && obj !== true && obj !== false) {
        NCUTCAT.warning("数据检查 - 返回数据非标准数据: ".yellow + obj);
    }
    if (obj.success === false) {
        obj.error && (obj.error = obj.error.sqlMessage || obj.error);
        obj.err && (obj.err = obj.err.sqlMessage || obj.err);
    }
    return obj;
}
global.DM_RES = (res, R = 'result', E = 'err', H) => {
    return async (e, r) => {
        if (e) e = e.sqlMessage || e
        else if (H) r = (H.constructor.name === 'AsyncFunction') ? (await H(r)) : H(r);
        let json = { success: !e };
        json[e ? E : R] = e ? e : r;
        return res.json(json);
    }
}

//exp 框架
let app = express();
app.use((req, res, next) => {
    NCUTCAT.infoLog('visit', `[${req.ip}]`.red + ` - ${req.url}`);
    next();
});

app.use(require('compression')()); //启用压缩传输
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());



//自动装载所有路由
let routeList = fs.readdirSync("./route/");
for (let key in routeList) {
    let name = routeList[key].replace(".js", "");
    app.use("/" + name, require("./route/" + name));
}

//基础根目录
app.use("/public", express.static("./public"));

//基础的根目录路由
app.get(["/public", "/l", "/", "/logined"], function(req, res) {
    res.redirect("/public/cloud-cat.html");
});
//帖子短链接
app.get(["/t/:k"], function(req, res) {
    let tid = (req.params || {}).k;
    let real = NCUTCAT.localProperty.publicContent_real_thread[tid];
    res.redirect(`/public/threads.html?tid=${real || tid}${real?'&real='+tid:''}`);
});

//初始化各个模块
(function initializationProm() {
    var host = NCUTCAT.localProperty.http_ip;
    var port = NCUTCAT.localProperty.http_port;

    if (host == "::") host = "0.0.0.0";

    //App Http listen
    app.listen(port, host, () => {
        NCUTCAT.infoLog("HTTP", "HTTP 模块监听: [ http://" + ((host || "127.0.0.1").yellow) + ":" + port + " ]");

        NCUTCAT.infoLog("INFO", "配置文件: property.js 文件");

        if (NCUTCAT.allError <= 0) {
            NCUTCAT.infoLog("INFO", "控制面板已经启动".green);
        } else {
            NCUTCAT.infoLog("INFO", "控制面板启动异常".red);
        }
    })
})();